/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.common.zxing.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.common.zxing.R;
import com.common.zxing.camera.CameraManager;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.Constants;

import java.util.ArrayList;
import java.util.Collection;

/**
 * This view is overlaid on top of the camera preview. It adds the viewfinder
 * rectangle and partial transparency outside it, as well as the laser scanner
 * animation and result points.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class ViewfinderView extends View {
    /**
     * 刷新界面的时间
     */
    private static final long ANIMATION_DELAY = 10L;
    private static final int OPAQUE = 0xFF;
    private static final int MAX_RESULT_POINTS = 5;
    /**
     * 四个绿色边角对应的长度
     */
    private int ScreenRate;

    /**
     * 四个绿色边角对应的宽度
     */
    private static final int CORNER_WIDTH = 8;
    /**
     * 扫描框中的中间线的宽度
     */
    private static final int MIDDLE_LINE_WIDTH = 6;

    /**
     * 扫描框中的中间线的与扫描框左右的间隙
     */
    private static final int MIDDLE_LINE_PADDING = 5;

    /**
     * 中间那条线每次刷新移动的距离
     */
    private static final int SPEEN_DISTANCE = 6;

    /**
     * 手机的屏幕密度
     */
    private static float density;
    /**
     * 字体大小
     */
    private static final int TEXT_SIZE = 12;
    /**
     * 字体距离扫描框下面的距离
     */
    private static final int TEXT_PADDING_TOP = 25;

    /**
     * 画笔对象的引用
     */
    private Paint paint;

    /**
     * 中间滑动线的最顶端位置
     */
    private int slideTop;

    /**
     * 中间滑动线的最底端位置
     */
    private int slideBottom;

    /**
     * 将扫描的二维码拍下来，这里没有这个功能，暂时不考虑
     */
    private Bitmap resultBitmap;
    private int maskColor;
    private int resultColor;

    private int resultPointColor;
    private Collection<ResultPoint> possibleResultPoints;
    private Collection<ResultPoint> lastPossibleResultPoints;
    private CameraManager cameraManager;
    boolean isFirst;
    boolean needAnim;//是否需要扫描动画

    private String strHint;

    private Rect frame;

    //手电筒相关
    private Bitmap flashLightBitmap;
    private Bitmap openFlashLightBitmap;
    private float flashLightBottomDistance;
    private Paint flashLightTextPaint;
    private int UNIT = 20;
    private Rect flashRect;
    private Rect flashOpenRect;
    private onFlashLightStateChangeListener mOnFlashLightStateChangeListener;


    public ViewfinderView(Context context) {
        this(context, null);
    }

    // This constructor is used when the class is built from an XML resource.
    public ViewfinderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public ViewfinderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // Initialize these once for performance rather than calling them every
        // time in onDraw().
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskColor = 0x66000000;
        resultColor = 0x66000000;
        resultPointColor = 0xc0ffff00;
        possibleResultPoints = new ArrayList<ResultPoint>(5);
        lastPossibleResultPoints = null;

        density = context.getResources().getDisplayMetrics().density;
        // 将像素转换成dp
        ScreenRate = (int) (10 * density);
        strHint = getResources().getString(R.string.bottom_hint);

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.burce);
        needAnim = array.getBoolean(R.styleable.burce_needAnim, true);


        flashLightBitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.icon_flash_off)).getBitmap();
        openFlashLightBitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.icon_flash_on)).getBitmap();
        flashLightBottomDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, UNIT * density, context.getResources().getDisplayMetrics());
        flashRect = new Rect();
        flashOpenRect = new Rect();
        flashLightTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        flashLightTextPaint.setColor(Color.WHITE);
        flashLightTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, TEXT_SIZE * density, context.getResources().getDisplayMetrics()));

    }

    public void setCameraManager(CameraManager cameraManager) {
        this.cameraManager = cameraManager;
    }

    @SuppressLint("NewApi")
    @Override
    public void onDraw(Canvas canvas) {
        // 中间的扫描框，你要修改扫描框的大小，去CameraManager里面修改
        if (cameraManager == null) {
            return;
        }
        frame = cameraManager.getFramingRect();
        if (frame == null) {
            return;
        }

        // 初始化中间线滑动的最上边和最下边
        if (!isFirst) {
            isFirst = true;
            slideTop = frame.top;
            slideBottom = frame.bottom;
        }

        // 获取屏幕的宽和高
        int width = canvas.getWidth();
        int height = canvas.getHeight();

        paint.setColor(resultBitmap != null ? resultColor : maskColor);


        // 画出扫描框外面的阴影部分，共四个部分，扫描框的上面到屏幕上面，扫描框的下面到屏幕下面
        // 扫描框的左边面到屏幕左边，扫描框的右边到屏幕右边
        canvas.drawRect(0, 0, width, height, paint);
//        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
//        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
//        canvas.drawRect(0, frame.bottom + 1, width, height, paint);


        paint.setColor(0x00000000);
        //覆盖删除下面的画面
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        //绘制圆角矩形
        RectF r2 = new RectF();                           //RectF对象
        r2.left = frame.left;                                 //左边
        r2.top = frame.top;                                 //上边
        r2.right = frame.right;                                   //右边
        r2.bottom = frame.bottom;                              //下边
        canvas.drawRoundRect(r2, 16, 16, paint);        //绘制圆角矩形

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));

        if (resultBitmap != null) {
            // Draw the opaque result bitmap over the scanning rectangle
            paint.setAlpha(OPAQUE);
            canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
        } else {

            // 绘制边框线
//            paint.setColor(0x00ffffff);//透明
//
//            canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
//            canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
//            canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
//            canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);

            // 这里画取景框四个角落的夹角

            paint.setAntiAlias(true);


            paint.setColor(0xffffffff);


//            //左上
//            canvas.drawRect(frame.left + ScreenRate
//                    - CORNER_WIDTH + 2, frame.top - CORNER_WIDTH + 2, frame.left + 100 - CORNER_WIDTH + 2, frame.top + 2, paint);
//            //左下
//            canvas.drawRect(frame.left - CORNER_WIDTH + 2, frame.top
//                    + ScreenRate - CORNER_WIDTH + 2, frame.left + 2, frame.top + 100 - CORNER_WIDTH + 2, paint);

//            canvas.drawRect(frame.right - 100 + CORNER_WIDTH - 2, frame.top - CORNER_WIDTH + 2, frame.right - ScreenRate + CORNER_WIDTH - 2, frame.top + 2, paint);
//            canvas.drawRect(frame.right - 2, frame.top
//                    + ScreenRate - CORNER_WIDTH + 2, frame.right + CORNER_WIDTH - 2, frame.top + 100 - CORNER_WIDTH + 2, paint);
//
//            canvas.drawRect(frame.left + ScreenRate - CORNER_WIDTH + 2, frame.bottom - 2,
//                    frame.left + 100 - CORNER_WIDTH + 2, frame.bottom + CORNER_WIDTH - 2, paint);
//            canvas.drawRect(frame.left - CORNER_WIDTH + 2, frame.bottom - 100 + CORNER_WIDTH - 2,
//                    frame.left + 2, frame.bottom - ScreenRate + CORNER_WIDTH - 2, paint);
//
//            canvas.drawRect(frame.right - 100 + CORNER_WIDTH
//                    - 2, frame.bottom - 2, frame.right - ScreenRate + CORNER_WIDTH - 2, frame.bottom + CORNER_WIDTH - 2, paint);
//            canvas.drawRect(frame.right - 2, frame.bottom - 100 + CORNER_WIDTH - 2, frame.right + CORNER_WIDTH
//                    - 2, frame.bottom - ScreenRate + CORNER_WIDTH - 2, paint);


//            canvas.drawRect(50, 400, 450, 600, paint);      //绘制矩形

            //绘制圆弧（夹角弧度）
            paint.setColor(0xffffffff);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(CORNER_WIDTH);


            //通过path路径绘制圆角夹角
            Path path = new Path();
            //左上
            path.moveTo(frame.left, frame.top + 100 - CORNER_WIDTH + 2);
            path.lineTo(frame.left, frame.top + ScreenRate);
            path.quadTo(frame.left, frame.top, frame.left + ScreenRate, frame.top);
            path.lineTo(frame.left + 100 - CORNER_WIDTH + 2, frame.top);
            canvas.drawPath(path, paint);

            //右上
            path.moveTo(frame.right - 100 + CORNER_WIDTH - 2, frame.top);
            path.lineTo(frame.right - ScreenRate, frame.top);
            path.quadTo(frame.right, frame.top, frame.right, frame.top + ScreenRate);
            path.lineTo(frame.right, frame.top + 100 - CORNER_WIDTH + 2);
            canvas.drawPath(path, paint);
            //右下
            path.moveTo(frame.right, frame.bottom - 100 + CORNER_WIDTH - 2);
            path.lineTo(frame.right, frame.bottom - ScreenRate);
            path.quadTo(frame.right, frame.bottom, frame.right - ScreenRate, frame.bottom);
            path.lineTo(frame.right - 100 + CORNER_WIDTH - 2, frame.bottom);
            canvas.drawPath(path, paint);
            //左下
            path.moveTo(frame.left + 100 + CORNER_WIDTH - 2, frame.bottom);
            path.lineTo(frame.left + ScreenRate, frame.bottom);
            path.quadTo(frame.left, frame.bottom, frame.left, frame.bottom - ScreenRate);
            path.lineTo(frame.left, frame.bottom - 100 - CORNER_WIDTH + 2);
            canvas.drawPath(path, paint);


            //左上
//            canvas.drawArc(new RectF(frame.left - 2, frame.top - 2, frame.left + 50, frame.top + 50), 180, 90, false, paint);
            //右上
//            canvas.drawArc(new RectF(frame.right - 50 - 2, frame.top - 2, frame.right + 2, frame.top + 50), -90, 90, false, paint);
//            //左下
//            canvas.drawArc(new RectF(frame.left - 2, frame.bottom - 50 + 2, frame.left + 50, frame.bottom + 2), 90, 90, false, paint);
//            //右下
//            canvas.drawArc(new RectF(frame.right - 50 + 2, frame.bottom - 50 + 2, frame.right + 2, frame.bottom + 2), 0, 90, false, paint);


//            canvas.drawRoundRect(100, 800, 900, 1200, 16, 16, paint);      //绘制矩形

            // 绘制中间的线,每次刷新界面，中间的线往下移动SPEEN_DISTANCE
            slideTop += SPEEN_DISTANCE;
            if (slideTop >= frame.bottom) {
                slideTop = frame.top;
            }

            Rect lineRect = new Rect();
            lineRect.left = frame.left;
            lineRect.right = frame.right;
            if (needAnim) {
                lineRect.top = slideTop;
                lineRect.bottom = slideTop + 18;
            } else {
                lineRect.top = slideBottom - (slideBottom - slideTop) / 2;
                lineRect.bottom = slideBottom - (slideBottom - slideTop) / 2 + 18;
            }
            canvas.drawBitmap(((BitmapDrawable) (getResources().getDrawable(R.drawable.scan_laserred))).getBitmap(),
                    null, lineRect, paint);

            /** 不显示关键点
             Collection<ResultPoint> currentPossible = possibleResultPoints;
             Collection<ResultPoint> currentLast = lastPossibleResultPoints;
             if (currentPossible.isEmpty()) {
             lastPossibleResultPoints = null;
             } else {
             possibleResultPoints = new HashSet<ResultPoint>(5);
             lastPossibleResultPoints = currentPossible;
             paint.setAlpha(OPAQUE);
             paint.setColor(resultPointColor);
             for (ResultPoint point : currentPossible) {
             canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint);
             }
             }
             if (currentLast != null) {
             paint.setAlpha(OPAQUE / 2);
             paint.setColor(resultPointColor);
             for (ResultPoint point : currentLast) {
             canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint);
             }
             }
             */
            // 只刷新扫描框的内容，其他地方不刷新
            if (needAnim) {
                postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom);
            }


            paint = new Paint();

            //画扫描框下面的字
            paint.setColor(Color.WHITE);
            paint.setTextSize(TEXT_SIZE * density);
            paint.setTextAlign(Align.CENTER);
            canvas.drawText(strHint, width / 2, frame.bottom + (float) TEXT_PADDING_TOP * density, paint);
//			canvas.drawText(getResources().getString(R.string.bottom_hint2), width / 2, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density*1.5), paint);


            if (Constants.isWeakLight) {

                if (!Constants.isFlashOn) {

                    flashRect.left = (width - flashLightBitmap.getWidth()) / 2;
                    flashRect.right = (width + flashLightBitmap.getWidth()) / 2;
                    flashRect.bottom = (int) (frame.bottom - flashLightBottomDistance);
                    flashRect.top = (int) (frame.bottom - flashLightBottomDistance - flashLightBitmap.getHeight());
                    canvas.drawBitmap(flashLightBitmap, null, flashRect, paint);
                }
            }

            if (Constants.isFlashOn) {
                flashOpenRect.left = (width - openFlashLightBitmap.getWidth()) / 2;
                flashOpenRect.right = (width + openFlashLightBitmap.getWidth()) / 2;
                flashOpenRect.bottom = (int) (frame.bottom - flashLightBottomDistance);
                flashOpenRect.top = (int) (frame.bottom - flashLightBottomDistance - openFlashLightBitmap.getHeight());
                canvas.drawBitmap(openFlashLightBitmap, null, flashOpenRect, paint);

            }


        }
    }

    public void reOnDraw() {
        if (null != frame) {
            postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
                    frame.right, frame.bottom);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    public void drawViewfinder() {
        Bitmap resultBitmap = this.resultBitmap;
        this.resultBitmap = null;
        if (resultBitmap != null) {
            resultBitmap.recycle();
        }
        invalidate();
    }


    public void drawTextHint(String str) {
        strHint = str;
        invalidate();
    }

    /**
     * Draw a bitmap with the result points highlighted instead of the live
     * scanning display.
     *
     * @param barcode An image of the decoded barcode.
     */
    public void drawResultBitmap(Bitmap barcode) {
        resultBitmap = barcode;
        invalidate();
    }

    public void addPossibleResultPoint(ResultPoint point) {
        possibleResultPoints.add(point);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();
//        if (!Constants.isFlashOn) {
//           boolean b = openFlashLight(x, y);
//        }
        if (null != mOnFlashLightStateChangeListener && openFlashLight(x, y)) {
            mOnFlashLightStateChangeListener.openFlashLight(Constants.isFlashOn);
        }
        return super.onTouchEvent(event);
    }


    private boolean openFlashLight(int x, int y) {
        Rect rect = flashRect;
        rect.left = flashRect.left - 10;
        rect.right = flashRect.right + 10;
        rect.top = flashRect.top - 10;
        rect.bottom = flashRect.bottom + 10;
        return rect.contains(x, y);
    }


    public interface onFlashLightStateChangeListener {
        void openFlashLight(boolean open);
    }

    public void setOnFlashLightStateChangeListener(onFlashLightStateChangeListener onFlashLightStateChangeListener) {
        mOnFlashLightStateChangeListener = onFlashLightStateChangeListener;
    }
}
